package com.firefightingiot.firefightingiot.config.dahua;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.cache.RedisUtil;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: YangYu
 * @ClassName: dahua
 * @Date: Created in 17:02 2022/1/20
 * @Description: 大华
 */
@Component
public class DaHua extends BaseService {
    //秘钥
    String client_id = "re71114dc1107d4572a6e581131601145a";
    String client_secret = "02715e2e11065d58568ce7ae02ffef61";
    @Resource
    RedisUtil redisUtil;
    @Resource
    public MyLogger logger;


    /**
     * @Author YangYu
     * @Description 获取token
     * @Date Created in 17:04 2022/1/20
     * @Param []
     */

    public String getDaHuaYunRuiToken() throws ParseException {
        //获取accessToken的参数
        cn.hutool.core.lang.Dict dict = new cn.hutool.core.lang.Dict();
        dict.set("grant_type", "client_credentials");
        dict.set("scope", "server");
        dict.set("client_id", client_id);
        dict.set("client_secret", client_secret);
        Map<String, Object> map = new HashMap<>();
        if (!redisUtil.exists("DHYRTOKEN")) {
            com.alibaba.fastjson.JSONObject accessToken = dahua(dict, "dahua", "token", "DaHuaYunRui", "POST");
            logger.info("token信息:" + accessToken.toString());
            map.put("accessToken", accessToken.getString("access_token"));
            map.put("time", DateUtil.now());
            redisUtil.set("DHYRTOKEN", map);
        }
        Map<String, Object> jsonObject = (Map<String, Object>) redisUtil.get("DHYRTOKEN");

        if (getNMinute(jsonObject.get("time").toString())) {
            com.alibaba.fastjson.JSONObject accessToken = dahua(dict, "dahua", "token", "DaHuaYunRui", "POST");
            logger.info("token信息:" + accessToken.toString());
            map.put("accessToken", accessToken.getString("access_token"));
            map.put("time", DateUtil.now());
            redisUtil.set("DHYRTOKEN", map);
            jsonObject = (Map<String, Object>) redisUtil.get("weChat");
        }
        return jsonObject.get("accessToken").toString();
    }

    /**
     * @Author YangYu
     * @Description 获取直播视频流地址
     * @Date Created in 11:30 2022/1/21
     * @Param [number]
     */

    public String getRtmp(String number) throws ParseException {
        //获取token
        String token = getDaHuaYunRuiToken();
        JSONObject deviceInfoObj = new JSONObject();
        deviceInfoObj.put("deviceId",number);
        //获取单个设备详情
        JSONObject deviceInfo = restDHYR(deviceInfoObj,"dahua","deviceInfo","DaHuaYunRui",token,"POST");
        JSONObject channelIdObj = (JSONObject) deviceInfo.getJSONObject("data").getJSONArray("channelList").get(0);
        String channelId = channelIdObj.getStr("channelId");
        deviceInfoObj.put("channelId",channelId);
        //获取视频流
        JSONObject live = restDHYR(deviceInfoObj,"dahua","live","DaHuaYunRui",token,"POST");
        //视频流
        String rtmp = "";
        if ("0".equals(live.getStr("code"))){
            JSONObject object = (JSONObject) live.getJSONObject("data").getJSONArray("streams").get(0);
            rtmp = object.getStr("hls");
        }else {
            JSONObject liveInfo = restDHYR(deviceInfoObj,"dahua","liveInfo","DaHuaYunRui",token,"POST");
            JSONObject object = (JSONObject) liveInfo.getJSONObject("data").getJSONArray("streams").get(0);
            rtmp = object.getStr("hls");
        }
        return rtmp;
    }

    /**
     * @Author YangYu
     * @Description 校验token时间是否到期
     * @Date Created in 10:04 2022/1/21
     * @Param [oldDateStr]
     */

    public static boolean getNMinute(String oldDateStr) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int minute = calendar.get(Calendar.MINUTE);
        calendar.set(Calendar.MINUTE, minute - 8640);
        Date newDate = new Date(calendar.getTimeInMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date oldDate = simpleDateFormat.parse(oldDateStr);
        return newDate.getTime() >= oldDate.getTime();
    }
}
